<template>
  <div class="evaluation">
    <el-card header="服务评价">
      <el-table :data="orderItemList" v-if="orderItemList.length>0" :height="tableHeight">
        <el-table-column label="名称" width="160" align="center" prop="productName"/>
        <el-table-column label="图片" align="center" prop="pic" :show-overflow-tooltip="true">
          <template #default="{row}">
            <span v-if="row.productPic===''">暂无</span>
            <el-image v-else :src="row.productPic" style="width: 60px; height: 60px" fit="fill"
                      :preview-src-list="[row.productPic]"/>
          </template>
        </el-table-column>
        <el-table-column label="服务店面" width="200" align="center" prop="serviceStoreName"/>
        <el-table-column label="所属品牌" width="200" align="center" prop="brandName"/>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="{row}">
            <el-button size="mini" type="text" icon="el-icon-edit" @click="startEvaluation(row)">评价
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-empty v-else description="全部评价完了哦~">
      </el-empty>
      <el-row>
        <el-col :span="20"></el-col>
        <el-col :sapn="4">
          <m-button style="float: right;margin-top: 10px" text="返回" @click="toMemberCenter"
                    classStyle="main-btn"></m-button>
        </el-col>
      </el-row>
    </el-card>

    <!--评价弹框-->
    <el-dialog title="评价" v-model="openEvaluation" width="60%">
      <el-form :model="orderEvaluationForm" ref="evaluationFormRef" :rules="formRules">
        <el-row>
          <el-col :span="24">
            <el-form-item label="图片" prop="pics">
              <el-upload ref="picUploadRef" class="up-img-uploader" :action="imageAction" list-type="picture-card"
                         :on-success="handleUploadSuccess" :headers="headers" :on-remove="handleRemove">
                <i class="el-icon-plus avatar-uploader-icon"/>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="24">
            <el-form-item label="评分" style="margin-top: 10px" prop="star">
              <el-rate v-model="orderEvaluationForm.star" show-text :texts="['极差', '失望', '一般', '满意', '非常满意']"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="评价内容" prop="content">
              <el-input v-model="orderEvaluationForm.content" type="textarea" rows="4" placeholder="评论内容" clearable
                        :autosize="{ minRows: 4, maxRows: 10 }">
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancel">取 消</el-button>
          <el-button type="primary" @click="submit">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { getToken } from '../../utils/auth'
import { useRoute, useRouter } from 'vue-router'
import { reactive, toRefs, onMounted, ref } from 'vue'
import orderApi from '../../api/order'
import MButton from '../../components/MButton.vue'
import orderEvaluaionApi from '../../api/orderEvaluaion'
import { ElMessage, ElMessageBox } from 'element-plus'

export default {
  name: 'Evaluation',
  components: {
    MButton
  },
  setup () {
    const route = useRoute()
    const router = useRouter()
    const state = reactive({
      // 订单项
      orderItemList: [],
      tableHeight: window.innerHeight - 500,
      openEvaluation: false,
      // 当前的订单项
      currentOrderItem: null,
      orderEvaluationForm: {
        pics: '',
        content: '',
        star: 0
      },
      // 请求地址
      imageAction: '/api/file/upload', // 上传的图片服务器地址
      headers: {
        // 上传文件的请求头
        Authorization: 'Bearer ' + getToken()
      },
      // 存放临时的轮播图
      picList: [],
      formRules: {
        star: [{ required: true, trigger: 'change', message: '评分不能为空' }],
        content: [{ required: true, trigger: 'change', message: '评价不能为空' }],
        pics: [{ required: true, trigger: 'change', message: '图片不能为空' }]
      },
    })
    // 表单使用
    let evaluationFormRef = ref(null)
    // 图片上传组件
    let picUploadRef = ref(null)
    //---------------------method start
    let orderId = route.query.orderId
    // 获取所有未评价订单项
    const getNotEvaluationMemberOrderItems = async () => {
      const res = await orderApi.getNotEvaluationMemberOrderItems(orderId)
      state.orderItemList = res.data
      // console.log(res)
    }
    // 开始评价
    const startEvaluation = (row) => {
      // console.log(row)
      state.currentOrderItem = row
      state.openEvaluation = true
    }
    // 处理上传成功
    const handleUploadSuccess = (res, file) => {
      if (res.code === 200) {
        state.picList.push({
          uid: file.uid,
          url: res.data.url
        })
      }
    }
    // 处理移除
    const handleRemove = () => {
      // 根据uid去删除
      state.picList.splice(
          state.picList.findIndex(e => e.uid === file.uid)
      )
    }
    // 取消表单
    const cancel = () => {
      evaluationFormRef.value.resetFields()
      state.currentOrderItem = null
      state.picList = []
      // 清除缓存
      picUploadRef.value.clearFiles()
      state.openEvaluation = false
    }
    // 提交表单
    const submit = () => {
      // 图片逗号拼接
      let picStr = ''
      state.picList.forEach(e => {
        picStr += e.url + ','
      })
      picStr = picStr.substring(0, picStr.lastIndexOf(','))
      state.orderEvaluationForm.pics = picStr
      state.orderEvaluationForm.orderId = orderId
      state.orderEvaluationForm.orderItemId = state.currentOrderItem.id
      evaluationFormRef.value.validate(valid => {
        if (valid) {
          orderEvaluaionApi.saveMemberOrderEvaluation(state.orderEvaluationForm).then(res => {
            ElMessage.success('评价成功,感谢您的评价~')
            // 刷新页面
            getNotEvaluationMemberOrderItems()
            evaluationFormRef.value.resetFields()
            state.currentOrderItem = null
            state.picList = []
            // 清除缓存
            picUploadRef.value.clearFiles()
            state.openEvaluation = false
          })
        }
      })
    }
    // 去个人中心
    const toMemberCenter = () => {
      router.push('/member/center')
    }
    //---------------------method end

    //----------------钩子
    onMounted(() => {
      getNotEvaluationMemberOrderItems()
    })

    return {
      ...toRefs(state),
      picUploadRef,
      evaluationFormRef,
      startEvaluation,
      handleRemove,
      handleUploadSuccess,
      toMemberCenter,
      cancel,
      submit
    }
  }
}
</script>

<style scoped lang="scss">
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.up-img-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #000000;
  background-color: #e8e8e8;
  width: 148px;
  height: 148px;
  line-height: 148px;
  text-align: center;
}

.up-img {
  width: 148px;
  height: 148px;
  display: block;
}
</style>
